<template>
  <div class="common-layout">
    <el-container class="container">
      <el-aside class="left-aside">
        <MunuCom :collapse="MenuToggle" ></MunuCom>
      </el-aside>
      <el-container>
        <el-header class="header">
          <el-button type="danger" class="menu-toggle" link @click="MenuToggle = !MenuToggle">
            <el-icon>
              <component @click="change" :is="MenuToggle ? 'Sunny' : 'Moon'"></component>
            </el-icon>
          </el-button>
          <el-dropdown v-if="loginStatus">
            <el-space class="header-user">
              欢迎你:{{ userInfo?.nickname }}
              <el-avatar :src="userInfo?.avatarUrl" />
            </el-space>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  @click="$router.push('/personalindex/personal/personalinfosettings')">设置</el-dropdown-item>
                <el-dropdown-item @click="logoutHandler">登出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button type="primary" v-else link @click="login">登录</el-button>
        </el-header>
        <el-main class="main">

          <BreadCrumb></BreadCrumb>
          <router-view></router-view>
        </el-main>
        <el-footer class="footer">
          <aplayer></aplayer>

        </el-footer>
      </el-container>

    </el-container>
  </div>
</template>

<script>
import { Expand, Fold ,Sunny,Moon} from '@element-plus/icons-vue'
import { qrKeyInterface, qrCreateInterface, qrCheckInterface, loginStatusInterface, logoutInterface } from '@/api/user';
import { mapState, mapMutations } from 'vuex'
import { computed } from 'vue'
import MunuCom from '@/components/MenuCom.vue'
import aplayer from '@/components/AplayerCom.vue'
import BreadCrumb from '@/components/BreadCrumbCom.vue'
import { useDark, useToggle } from '@vueuse/core'

const isDark = useDark({
  selector: 'html',
  attribute: 'class',
  valueDark: 'dark',
  valueLight: 'light',
})
const toggleDark = useToggle(isDark)

export default {
  data() {
    return {
      // 二维码key
      unikey: '',
      // base64的二维码图片路径
      qrSrc: '',
      // 轮询id定时器
      qrTimer: '',
      // 搜索内容
      searchResult: '',
      searchList: [],
      MenuToggle: false,
      defaultActiveMenu: ''
    }
  },
  components: {
    MunuCom,
    aplayer,
    BreadCrumb,
    Expand,
    Fold,
    Sunny,
    Moon
  },
  provide() {
    return {
      // 响应式关键
      searchResult: computed(() => this.searchResult)
    }
  },
  methods: {
    change() { 
      toggleDark();

    },

    // mapMutations
    ...mapMutations('userInfoModule', ['SET_USER', 'USER_STATUS']),

    async login() {
      // 登录接口
      // 通过qrkey接口生成qrkey
      const qrkeyRes = await qrKeyInterface()
      this.unikey = qrkeyRes.data.unikey
      // 传入上一步生成的key
      const qrSrcRes = await qrCreateInterface({
        key: this.unikey,
        qrimg: import('/favicon.ico')
      })
      // 通过传入qrimg参数获取到base64格式的二维码图片
      this.qrSrc = qrSrcRes.data.qrimg
      /* 
        轮询二维码扫码状态
           800 为二维码过期, 801 为等待扫码, 802 为待确认,
           803 为授权登录成功(803 状态码下会返回 cookies) 
      */
      ElMessageBox.alert(
        // 这里不支持 el-image组件 只能使用原生 <img/>
        `<div style='display:flex; justify-content:center;align-items:center'>
          <img src="${qrSrcRes.data.qrimg}" />
          <img src="https://p5.music.126.net/obj/wo3DlcOGw6DClTvDisK1/9643571155/525c/faac/2dc6/fe695c03c7c358ddaa4651736b26a55f.png" style="width:200px;object-fit:contain">
          </div>
        `,
        '扫码登录',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: 'OK',
          customStyle: 'text-align:center',
          showConfirmButton:false,

          callback: (action) => {
            clearInterval(this.qrTimer)
            ElMessage({
              type: 'info',
              message: `action: ${action}`,
            })
          },

        }
      )
      this.pollData();


    },
    // 轮询二维码登录接口
    pollData() {
      this.qrTimer = setInterval(async () => {
        const qrCheckRes = await qrCheckInterface({ key: this.unikey });
        switch (qrCheckRes.code) {
          case 803:
            localStorage.setItem('cookie', qrCheckRes.cookie)
            console.log('扫码成功!');
            // 关闭ElMessageBox二维码弹窗
            ElMessageBox.close()
            ElMessage.success('扫码登录成功!')
            // 更新右上角信息
            this.getloginStatus()
            console.log(this.userInfo);
            // 显示右上角用户信息
            this.USER_STATUS(true)

            document.cookie = `cookie=${qrCheckRes.cookie};expires=  ${new Date(new Date().getTime() + 24 * 60 * 60 * 1000).toUTCString()}`;
            clearInterval(this.qrTimer)
            break;
          case 800:
            console.log('QR 码已过期');
            ElMessage({
              message: '二维码已过期!',
              type: 'error',
              showClose: true,
              duration:0
             })

            clearInterval(this.qrTimer)
            break;
          case 801:
            console.log('等待扫码中...');
            break;
          case 802:
            console.log('扫码成功，等待确认中...');
            break;
          default:
            break;
        }
      }, 1000);
    },
    // 登出接口
    logoutHandler() {
      logoutInterface({
      }).then(res => {
        console.log(res);
        ElMessage({
          message: res.code === 200 ? '您已退出' : '暂时无法退出',
          type: res.code === 200 ? 'success' : 'error'
        })
        localStorage.removeItem('cookie');
        localStorage.removeItem('vuex');
        this.USER_STATUS(false);
        this.$router.push('/')
      })
    },
    // 登录状态接口
    getloginStatus() {
      loginStatusInterface({
        cookie: localStorage.getItem('cookie')
      }).then(res => {

        this.SET_USER(res.data.profile)
        this.uid = this.userInfo.userId;
      })
    },
  },
  computed: {
    ...mapState('userInfoModule', ["userInfo", 'loginStatus'])
  },
  watch: {
    $route: {
      immediate: true,
      handler(currentRoute) {
        this.defaultActiveMenu = currentRoute.name
      }
    }
  }

}
</script>

<style lang="scss" scoped>
.menu-toggle {
  font-size: 20px;
}

.el-aside {
  width: v-bind(sdafsaf);
  transition: .5s;
}

.common-layout {
  height: 100vh;

  .container {
    height: 100%;

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #EC4141;

      .header-user {
        color: #fff;
      }
    }


  }
}

</style>
